package com.tang.websocket.v1.handler;

import com.tang.websocket.v1.message.WebSocketMessage;
import com.tang.websocket.v1.session.SessionManagerSupport;
import com.tang.websocket.v1.session.SessionPath;
import com.tang.websocket.v1.session.SimpleSessionManagerSupport;
import com.tang.websocket.v1.session.WebSocketSession;

import java.io.IOException;

/**
 * @author Tang
 * @classname AbstractWebSocketHandler
 * @description [  ]
 * @date 2022/11/29 23:47
 */
public abstract class AbstractWebSocketHandler implements WebSocketHandler {

    /**
     * session 的管理
     */
    protected final SessionManagerSupport sessionManagerSupport = new SimpleSessionManagerSupport();

    /**
     * session key
     */
    private SessionPath sessionPath;

    @Override
    public void onOpen(WebSocketSession webSocketSession) {
        // 存储session的路径
        this.sessionPath = getSessionPath();
        // 存储session
        this.sessionManagerSupport.addSession(webSocketSession,this.sessionPath.buildKey(webSocketSession));
    }

    @Override
    public void onMessage(WebSocketSession webSocketSession, WebSocketMessage<?> message) throws IOException {
    }

    @Override
    public void onClose(WebSocketSession webSocketSession) {
        // 移除 session
        sessionManagerSupport.removeSession(sessionPath.buildKey(webSocketSession));
        // 关闭session
        try {
            webSocketSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onError(WebSocketSession webSocketSession, Throwable e) {
        onClose(webSocketSession);
    }

    public SessionManagerSupport getSessionManagerSupport() {
        return sessionManagerSupport;
    }

    public abstract SessionPath getSessionPath();
}
